package code.whmmm.util.hikari.jdbcpool;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.pool.HikariPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p><b>
 * hikariCP 连接池<br/>
 * pool.getConnection() 获取 数据库 jdbc 连接，<br/>
 * pool.evictConnection() 释放连接 .
 * </b></p>
 * <br/>
 * 创建时间: 8/14/2019 10:58 AM
 *
 * @author Zero
 */
public class JdbcPoolFactory {

    private JdbcPoolFactory() {
    }

    private static final String MYSQL_TYPE = "mysql";
    private static final Logger logger = LoggerFactory.getLogger(JdbcPoolFactory.class);

    /**
     * <ul>
     *     <li>mysql -默认 utf-8 编码</li>
     * </ul>
     *
     * @param config jdbc config
     * @return HikariPool
     */
    public static HikariPool createPool(JdbcPoolConfig config) {
        HikariConfig c = new HikariConfig();
        c.setMaximumPoolSize(config.getMax());
        c.setMinimumIdle(config.getMin());

        if (config.getDriver().contains(MYSQL_TYPE)) {
            c.setJdbcUrl(
                    "jdbc:mysql://" + config.getUrl() + "/" + config.getName() + "?useSSL=false&" +
                            "serverTimezone=GMT%2B8&useUnicode=true&" +
                            "characterEncoding=UTF-8&" +
                            // 支持 jdbc 批量操作
                            "rewriteBatchedStatements=true&" +
                            // 支持 ; 分割的 多条 sql 语句
                            "allowMultiQueries=true"
            );
        }

        c.setUsername(config.getUsername());
        c.setPassword(config.getPassword());
        c.setPoolName(config.getPoolName());
        c.setConnectionTimeout(config.getTimeout());

        HikariPool pool = null;

        try {
            pool = new HikariPool(c);
            logger.info(config.getPoolName() + " 初始化 成功！");

        } catch (Exception e) {
            logger.error(config.getPoolName() + " 初始化 失败！！！！！");
            logger.error(e.getMessage(), e);
        }

        return pool;
    }

}
